<template>
  <div class="dashboard-container">
    <!-- 欢迎标题 -->
    <div class="welcome-header">
      <h1>欢迎回来，管理员！</h1>
      <p class="current-time">{{ currentTime }}</p>
    </div>

    <!-- 数据概览卡片 -->
    <div class="row">
      <el-row :gutter="20">
        <!-- 用户数卡片 -->
        <el-col :span="6">
          <el-card class="data-card">
            <div class="card-content">
              <div class="icon-box" style="background-color: #f0f9eb">
                <el-icon color="#67C23A" :size="30"><User /></el-icon>
              </div>
              <div class="card-text">
                <h3>总用户数</h3>
                <p class="number">
                  <template v-if="loading">
                    <el-icon class="is-loading"><Loading /></el-icon>
                  </template>
                  <template v-else>
                    {{ userCount.toLocaleString() }}
                  </template>
                </p>
              </div>
            </div>
          </el-card>
        </el-col>

        <!-- 内容量卡片 -->
        <el-col :span="6">
          <el-card class="data-card">
            <div class="card-content">
              <div class="icon-box" style="background-color: #fdf6ec">
                <el-icon color="#E6A23C" :size="30"><Document /></el-icon>
              </div>
              <div class="card-text">
                <h3>总内容量</h3>
                <p class="number">
                  <template v-if="loading">
                    <el-icon class="is-loading"><Loading /></el-icon>
                  </template>
                  <template v-else>
                    {{ contentCount.toLocaleString() }}
                  </template>
                </p>
              </div>
            </div>
          </el-card>
        </el-col>

        <!-- 待审核卡片 -->
        <el-col :span="6">
          <el-card class="data-card">
            <div class="card-content">
              <div class="icon-box" style="background-color: #fef0f0">
                <el-icon color="#F56C6C" :size="30"><Tickets /></el-icon>
              </div>
              <div class="card-text">
                <h3>待处理审核</h3>
                <p class="number">
                  <template v-if="loading">
                    <el-icon class="is-loading"><Loading /></el-icon>
                  </template>
                  <template v-else>
                    {{ checkCount.toLocaleString() }}
                  </template>
                </p>
              </div>
            </div>
          </el-card>
        </el-col>

        <!-- 待举报卡片 -->
        <el-col :span="6">
          <el-card class="data-card">
            <div class="card-content">
              <div class="icon-box" style="background-color: #ecf5ff">
                <el-icon color="#409EFF" :size="30"><Money /></el-icon>
              </div>
              <div class="card-text">
                <h3>待处理举报</h3>
                <p class="number">
                  <template v-if="loading">
                    <el-icon class="is-loading"><Loading /></el-icon>
                  </template>
                  <template v-else>
                    {{ reportCount.toLocaleString() }}
                  </template>
                </p>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 图表区域 -->
    <div class="row">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-card>
            <h3>内容发布趋势</h3>
            <div ref="contentChartRef" class="chart-container"></div>
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card>
            <h3>举报趋势分析</h3>
            <div ref="reportChartRef" class="chart-container"></div>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import * as echarts from 'echarts'
import {
  User,
  Document,
  Tickets,
  Money,
  Loading,
} from '@element-plus/icons-vue'
import {
  countContent,
  countUser,
  countCheck,
  countReport,
  getReportTrend,
  getContentTrend,
} from '@/apis/count'

// 实时时间
const currentTime = ref('')

// 数据统计
const userCount = ref(0)
const contentCount = ref(0)
const checkCount = ref(0)
const reportCount = ref(0)
const loading = ref(true)

// 获取统计数据
const fetchData = async () => {
  try {
    loading.value = true

    // 并行请求所有数据
    const [contentRes, userRes, checkRes, reportRes] = await Promise.all([
      countContent(),
      countUser(),
      countCheck(),
      countReport(),
    ])

    // 赋值响应式数据
    contentCount.value = contentRes.data || 0
    userCount.value = userRes.data || 0
    checkCount.value = checkRes.data || 0
    reportCount.value = reportRes.data || 0
  } catch (error) {
    console.error('数据获取失败:', error)
    // 可以在这里添加错误提示
    ElMessage.error('数据加载失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 更新时间
const updateTime = () => {
  const now = new Date()
  currentTime.value = now.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: 'long',
    day: 'numeric',
    weekday: 'long',
    hour: '2-digit',
    minute: '2-digit',
  })
}
const contentChartRef = ref(null)
const reportChartRef = ref(null)
let contentChartInstance = null
let reportChartInstance = null

// 初始化内容趋势图表
const initContentChart = async () => {
  try {
    const res = await getContentTrend()
    const trendData = res.data || []

    const xData = trendData.map(
      (item) => `${item.year}-${item.month.toString().padStart(2, '0')}`
    )
    const yData = trendData.map((item) => item.count)
    const option = {
      tooltip: {
        trigger: 'axis',
        formatter: '{b}<br/>{c} 篇内容',
      },
      xAxis: {
        type: 'category',
        data: xData,
        axisLabel: {
          rotate: 45,
        },
      },
      yAxis: {
        type: 'value',
        name: '发布数量',
      },
      series: [
        {
          data: yData,
          type: 'line',
          smooth: true,
          areaStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: 'rgba(230, 162, 60, 0.8)' }, // 使用内容卡片的橙色
              { offset: 1, color: 'rgba(230, 162, 60, 0.1)' },
            ]),
          },
          itemStyle: {
            color: '#E6A23C',
          },
        },
      ],
      grid: {
        left: '3%',
        right: '4%',
        bottom: '15%',
        containLabel: true,
      },
    }

    if (contentChartRef.value) {
      contentChartInstance = echarts.init(contentChartRef.value)
      contentChartInstance.setOption(option)
      window.addEventListener('resize', () => {
        contentChartInstance.resize()
      })
    }
  } catch (error) {
    console.error('获取内容趋势失败:', error)
    ElMessage.error('内容趋势数据加载失败')
  }
}

// 修改举报趋势图表初始化（变量名需要调整）
const initReportChart = async () => {
  try {
    const res = await getReportTrend()
    const trendData = res.data || []

    const xData = trendData.map(
      (item) => `${item.year}-${item.month.toString().padStart(2, '0')}`
    )
    const yData = trendData.map((item) => item.count)

    // 配置图表选项
    const option = {
      tooltip: {
        trigger: 'axis',
        formatter: '{b}<br/>{c} 次举报',
      },
      xAxis: {
        type: 'category',
        data: xData,
        axisLabel: {
          rotate: 45,
        },
      },
      yAxis: {
        type: 'value',
        name: '举报数量',
      },
      series: [
        {
          data: yData,
          type: 'line',
          smooth: true,
          areaStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: 'rgba(64, 158, 255, 0.8)' },
              { offset: 1, color: 'rgba(64, 158, 255, 0.1)' },
            ]),
          },
          itemStyle: {
            color: '#409EFF',
          },
        },
      ],
      grid: {
        left: '3%',
        right: '4%',
        bottom: '15%',
        containLabel: true,
      },
    }

    if (reportChartRef.value) {
      reportChartInstance = echarts.init(reportChartRef.value)
      reportChartInstance.setOption(option)
      window.addEventListener('resize', () => {
        reportChartInstance.resize()
      })
    }
  } catch (error) {
    console.error('获取举报趋势失败:', error)
    ElMessage.error('举报趋势数据加载失败')
  }
}
onMounted(() => {
  updateTime()
  fetchData()
  initContentChart() // 初始化内容趋势图表
  initReportChart() // 初始化举报趋势图表
})

// 销毁图表实例
onBeforeUnmount(() => {
  // 销毁两个图表实例
  if (contentChartInstance) {
    contentChartInstance.dispose()
    window.removeEventListener('resize', contentChartInstance.resize)
  }
  if (reportChartInstance) {
    reportChartInstance.dispose()
    window.removeEventListener('resize', reportChartInstance.resize)
  }
})
</script>

<style scoped>
.dashboard-container {
  padding: 24px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 64px);
}

.welcome-header {
  margin-bottom: 24px;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.welcome-header h1 {
  margin: 0;
  color: #303133;
  font-size: 24px;
}

.current-time {
  margin: 8px 0 0;
  color: #909399;
  font-size: 14px;
}

.data-card {
  margin-bottom: 20px;
}

.card-content {
  display: flex;
  align-items: center;
}

.icon-box {
  padding: 12px;
  border-radius: 8px;
  margin-right: 16px;
}

.card-text h3 {
  margin: 0;
  color: #606266;
  font-size: 14px;
}

.card-text .number {
  margin: 8px 0 0;
  font-size: 24px;
  font-weight: bold;
  color: #303133;
}

.chart-placeholder {
  height: 300px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.row {
  margin-bottom: 20px;
}
.chart-container {
  height: 300px;
  width: 100%;
}
</style>
